package com.heima.kafka.sample;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * 流式处理
 */
public class KafkaStreamQuickStart {
    public static void main(String[] args) {
        //kafaka配置信息
        Properties properties = new Properties();
        properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-quickstart");
        //创建kafkastream对象
        StreamsBuilder streamsBuilder = new StreamsBuilder();
        //流式计算
        streamProcessor(streamsBuilder);
        Topology topology = streamsBuilder.build();
        KafkaStreams kafkaStrams = new KafkaStreams(topology, properties);
        //开启流式计算
        kafkaStrams.start();
    }

    /**
     * 流式计算
     *
     * @param streamsBuilder
     */
    private static void streamProcessor(StreamsBuilder streamsBuilder) {
        //创建kstream对象，同时指定从哪个topic中接收消息
        KStream<String, String> stream = streamsBuilder.stream("itcast_topic_input");
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    /**
                     * 处理消息的value值
                     * @param value the value to be mapped
                     * @return
                     */
                    @Override
                    public Iterable<String> apply(String value) {
                        String[] valueArray = value.split(" ");
                        return Arrays.asList(valueArray);
                    }
                })//按照value进行聚合处理
                .groupBy((key, value) -> value)
                //时间窗口
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //统计单词个数
                .count()
                //转换为stream对象
                .toStream().map((key, value) -> {
                    System.out.println("key:" + key +"value:"+value);
                    return new KeyValue<>(key.key().toString(), value.toString());
                })
                //发送消息
                .to("itcast_topic_out");
    }
}
